const app = getApp()
const request = require('../../../utils/request.js')
const util = require('../../../utils/util.js')
Page({
  data: {
    //地址列表，来自于网络和本地
    address: {},
    orderArr: [],
    orderStatus: -1,
    orderId: '',
    orderIdArr: [],
    status_title_list: [
      "订单已完成",
      "等待买家付款",
      "买家已付款",
      "卖家已发货",
      "等待卖家评价",
      "交易关闭"
    ],
    fromShopCart: false
  },
  onLoad: function(options) {
    /*
      order status:
      0 -> 已完成
      1 -> 待付款
      2 -> 待发货
      3 -> 待收货
      4 -> 待评价
      5 -> 交易关闭
    */
    var that = this;
    if (options.orderId) {
      console.log(options.orderId);
      var url = request.URL + '/order/byOrderId';
      var orderId = options.orderId;
      request.request({
        url: url,
        data: {
          orderId: orderId
        },
        success: function(res) {
          console.log(res);
          var address = res.data.address;
          var orderArr = [];
          var orderStatus = res.data.orderVO.order.orderStatus;
          orderArr.push(res.data.orderVO);
          for (var i = 0; i < (res.data.orderVO.goodVOS).length; i++) {
            var goodImgArray = res.data.orderVO.goodVOS[i].goodImgArray;
            var goodImgUrl = util.string2Array(goodImgArray)[0];
            res.data.orderVO.goodVOS[i].goodImgUrl = goodImgUrl;
          }
          that.setData({
            address: address,
            orderArr: orderArr,
            orderStatus: orderStatus,
            orderId: orderId
          })
          console.log(that.data.orderArr)
        },
        fail: function() {
          request.showFailInfo()
        }
      })
    } else {
      var orderItemsArr = app.globalData.orderItemsArr.orderItemsArr;
      var fromItemPage = app.globalData.orderItemsArr.orderItemsArr.fromItemPage;
      var orderStatus = app.globalData.orderItemsArr.orderStatus;
      console.log(app.globalData.orderItemsArr)
      if (fromItemPage) {
        that.createOrderFromItemPage(orderItemsArr);
      } else {
        that.createOrderFromShopCart(orderItemsArr);
      }
      that.setData({
        orderStatus: orderStatus
      })
    }
  },
  /**创建购物车订单，默认未付款 */
  createOrderFromShopCart: function(orderItemsArr) {
    var that = this;
    var userId = 1;
    var url = request.URL + '/order/create';
    var shopTrolleyIdArray = [];
    var addressId = orderItemsArr.addressId;
    console.log(addressId)
    for (var i = 0; i < orderItemsArr.length; i++) {
      var goodsArr = orderItemsArr[i].goodsArr;
      for (var j = 0; j < goodsArr.length; j++) {
        var shopTrolleyId = goodsArr[j].shopTrolleyId;
        shopTrolleyIdArray.push(shopTrolleyId);
      }
    }
    console.log(shopTrolleyIdArray);
    request.request({
      url: url,
      data: {
        userId: userId,
        shopTrolleyIdArray: shopTrolleyIdArray,
        addressId: addressId
      },
      success: function(res) {
        console.log(res);
        var address = res.data.address;
        var allCountPrice = res.data.allCountPrice;
        var orderArr = res.data.orderVOS;
        //临时 
        var orderIdArr = [];
        console.log(orderArr)
        for (var i = 0; i < orderArr.length; i++) {
          var goodsArr = orderArr[i].goodVOS;
          orderIdArr.push(orderArr[i].order.orderId);
          for (var j = 0; j < goodsArr.length; j++) {
            var goodImgUrl = util.string2Array(goodsArr[j].goodImgArray)[0];
            orderArr[i].goodVOS[j].goodImgUrl = goodImgUrl;
          }
        }
        that.setData({
          address: address,
          allCountPrice: allCountPrice,
          orderArr: orderArr,
          orderIdArr: orderIdArr,
          fromShopCart: true
        })
        console.log(that.data.orderArr)
      },
      fail: function() {
        request.showFailInfo()
      }
    })

  },
  /**创建商品页订单，默认未付款 */
  createOrderFromItemPage: function(orderItemsArr) {
    var that = this;
    var goodId = orderItemsArr[0].goodsArr[0].goodId;
    var userId = 1;
    var standard = orderItemsArr[0].goodsArr[0].standard;
    var goodCnt = orderItemsArr[0].goodsArr[0].goodCnt;
    var addressId = orderItemsArr.addressId;
    console.log(addressId)
    var url = request.URL + '/order/createOutright';
    request.request({
      url: url,
      data: {
        userId: userId,
        goodId: goodId,
        standard: standard,
        goodCnt: goodCnt,
        addressId: addressId
      },
      success: function(res) {
        console.log(res);
        var address = res.data.address;
        var allCountPrice = res.data.allCountPrice;
        var orderArr = res.data.orderVOS;
        var orderId = orderArr[0].order.orderId;
        for (var i = 0; i < orderArr.length; i++) {
          var goodsArr = orderArr[i].goodVOS;
          for (var j = 0; j < goodsArr.length; j++) {
            var goodImgUrl = util.string2Array(goodsArr[j].goodImgArray)[0];
            orderArr[i].goodVOS[j].goodImgUrl = goodImgUrl;
          }
        }
        that.setData({
          address: address,
          allCountPrice: allCountPrice,
          orderArr: orderArr,
          orderId: orderId,
          fromShopCart: false
        })
        console.log(that.data.orderArr)
      },
      fail: function() {
        request.showFailInfo()
      }
    })

  },
  /**进入地址选择页 */
  toAddrList: function(e) {
    wx.navigateTo({
      url: '/pages/address_list/address_list',
    })
  },

  /**点击删除订单 */
  deleteOrder: function(e) {
    var that = this;
    var orderId = e.currentTarget.dataset.orderid;
    console.log(orderId)
    wx.showModal({
      title: '删除订单',
      content: '删除的订单将无法恢复',
      success: function(res) {
        console.log(res)
        if (res.confirm) {
          var url = request.URL + '/order/delete';
          request.request({
            url: url,
            data: {
              orderId: orderId
            },
            success: function(res) {
              if (res.statusCode == 200) {
                wx.navigateBack({
                  delta: 1
                })
              }
            },
            fail: function() {
              request.showFailInfo()
            }
          })
        }
      }
    })
  },
  /**进入店铺 */
  toStore: function(e) {
    var storeId = e.currentTarget.dataset.storeid;
    wx.navigateTo({
      url: '/pages/details/shop_details/shop_details?storeId=' + storeId,
    })
  },
  /**点击付款按钮 */
  payForOrder: function(e) {
    var that = this;
    var fromShopCart = that.data.fromShopCart;
    var orderIdArr = that.data.orderIdArr;
    var pages = getCurrentPages();
    var previousPage = pages[pages.length - 2];
    console.log(previousPage.data.isOrderList)

    if (fromShopCart) {
      var flag = 0;
      var len_order = orderIdArr.length;

      /**模拟付款 */
      wx.showModal({
        title: '模拟付款',
        content: '点击确定：付款成功，点击取消：取消付款',
        confirmColor: '#7B68EE',
        success: function(res) {
          if (res.confirm) {
            var that = this;
            var url = request.URL + '/order/pay';
            for (var i = 0; i < orderIdArr.length; i++) {
              var orderId = orderIdArr[i];
              request.request({
                url: url,
                data: {
                  orderId: orderId
                },
                success: function(res) {
                  flag++;
                  if (flag == len_order) {
                    wx.showToast({
                      title: '付款成功',
                      icon: 'success'
                    })
                    wx.hideLoading();
                    if (previousPage.data.isOrderList) {
                      console.log('navigateBack')
                      wx.navigateBack({
                        delta: 1
                      })
                    } else {
                      wx.switchTab({
                        url: '/pages/order_list/order_list',
                      })
                    }
                  }
                },
                fail: function() {
                  request.showFailInfo()
                }
              })
            }
          }

          if (res.cancel) {
            console.log('取消付款')
            if (previousPage.data.isOrderList) {
              wx.navigateBack({
                delta: 1
              })
            } else {
              wx.switchTab({
                url: '/pages/order_list/order_list',
              })
            }
          }
        }
      })
    } else {
      var orderId = e.currentTarget.dataset.orderid;
      console.log(e)
      /**模拟付款 */
      wx.showModal({
        title: '模拟付款',
        content: '点击确定：付款成功，点击取消：取消付款',
        confirmColor: '#7B68EE',
        success: function(res) {
          console.log(res);
          if (res.confirm) {
            var that = this;
            var url = request.URL + '/order/pay';
            request.request({
              url: url,
              data: {
                orderId: orderId
              },
              success: function(res) {

                wx.showToast({
                  title: '付款成功',
                  icon: 'success'
                })
                wx.hideLoading();
                if (previousPage.data.isOrderList) {
                  wx.navigateBack({
                    delta: 1
                  })
                } else {
                  wx.switchTab({
                    url: '/pages/order_list/order_list',
                  })
                }
              },
              fail: function() {
                request.showFailInfo()
              }
            })
          }

          if (res.cancel) {
            console.log('取消付款')
            if (previousPage.data.isOrderList) {
              wx.navigateBack({
                delta: 1
              })
            } else {
              wx.switchTab({
                url: '/pages/order_list/order_list',
              })
            }
          }
        }
      })
    }

  },
  /**点击取消订单按钮 */
  cancelOrder: function(e) {
    var that = this;
    var fromShopCart = that.data.fromShopCart;
    var orderIdArr = that.data.orderIdArr;
    var pages = getCurrentPages();
    var previousPage = pages[pages.length - 2];
    if (fromShopCart) {
      var flag = 0;
      var len_order = orderIdArr.length;
      wx.showModal({
        title: '取消订单',
        content: '点击确定取消订单',
        confirmColor: '#7B68EE',
        success: function(res) {
          if (res.confirm) {
            console.log('11111')
            var url = request.URL + '/order/close';
            for (var i = 0; i < orderIdArr.length; i++) {
              var orderId = orderIdArr[i];
              request.request({
                url: url,
                data: {
                  orderId: orderId
                },
                success: function(res) {

                  flag++;
                  if (flag == len_order) {
                    wx.showToast({
                      title: '取消订单成功',
                      icon: 'success'
                    })
                    wx.hideLoading();
                    if (previousPage.data.isOrderList) {
                      wx.navigateBack({
                        delta: 1
                      })
                    } else {
                      wx.switchTab({
                        url: '/pages/order_list/order_list',
                      })
                    }
                  }
                },
                fail: function() {
                  request.showFailInfo()
                }
              })
            }
          }

          if (res.cancel) {
            console.log('2222222')
            console.log('取消')
            if (previousPage.data.isOrderList) {
              wx.navigateBack({
                delta: 1
              })
            } else {
              wx.switchTab({
                url: '/pages/order_list/order_list',
              })
            }
          }
        }
      })
    } else {
      var orderId = e.currentTarget.dataset.orderid;
      wx.showModal({
        title: '取消订单',
        content: '点击确定取消订单',
        confirmColor: '#7B68EE',
        success: function(res) {
          if (res.confirm) {
            console.log('333333')
            var url = request.URL + '/order/close';
            request.request({
              url: url,
              data: {
                orderId: orderId
              },
              success: function(res) {

                wx.showToast({
                  title: '取消订单成功',
                  icon: 'success'
                })
                wx.hideLoading();
                if (previousPage.data.isOrderList) {
                  console.log('previousPage.data.isOrderList')
                  wx.navigateBack({
                    delta: 1
                  })
                } else {
                  wx.switchTab({
                    url: '/pages/order_list/order_list',
                  })
                }

              },
              fail: function() {
                request.showFailInfo()
              }
            })
          }


          if (res.cancel) {
            console.log('取消')
            console.log('444444')
            if (previousPage.data.isOrderList) {
              wx.navigateBack({
                delta: 1
              })
            } else {
              wx.switchTab({
                url: '/pages/order_list/order_list',
              })
            }
          }
        }
      })
    }

  },
  /**模拟发货 */
  simPayment: function(e) {
    var orderId = e.currentTarget.dataset.orderid;
    var that = this;
    var url = request.URL + '/order/sendGood';
    request.request({
      url: url,
      data: {
        orderId: orderId
      },
      success: function(res) {
        if (res.statusCode == 200) {
          wx.navigateBack({
            delta: 1
          })
          wx.navigateTo({
            url: '/pages/order_list/order_details/order_details?orderId=' + orderId,
          })
        }
      },
      fail: function() {
        request.showFailInfo()
      }
    })
  },
  /**确认收货 */
  confirmPayment: function(e) {
    var orderId = e.currentTarget.dataset.orderid;
    var that = this;
    var url = request.URL + '/order/signFor';
    request.request({
      url: url,
      data: {
        orderId: orderId
      },
      success: function(res) {
        if (res.statusCode == 200) {
          wx.navigateBack({
            delta: 1
          })
          wx.navigateTo({
            url: '/pages/order_list/order_details/order_details?orderId=' + orderId,
          })
        }
      },
      fail: function() {
        request.showFailInfo()
      }
    })
  },
  /**评价商品 */
  toCommentPage: function(e) {
    var that = this;
    var orderId = e.currentTarget.dataset.orderid;
    wx.navigateBack({
      delta: 1
    })
    wx.navigateTo({
      url: '/pages/write_comments/write_comments?orderId=' + orderId
    })
  },
  toServicePage: function(e) {
    console.log(e);
    var goodId = e.currentTarget.dataset.goodid;
    var orderId = e.currentTarget.dataset.orderid;
    var standard = e.currentTarget.dataset.standard;
    wx.navigateTo({
      url: '/pages/customer_service/apply_for_refund/apply_for_refund?orderId=' + orderId + '&goodId=' + goodId + '&standard=' + standard,
    })
  }
})